﻿//Created by Arcdemon//
//MapleCryptoAPI by aegisrunestone//
//Utilities class by aegisrunestone//
//Buffer class by aegisrunestone//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MapleCryptoAPI;
using Utility;
using UtilityClass;

namespace MaplePacketTool
{
    public partial class frmMaplePacket : Form
    {
        public frmMaplePacket()
        {
            InitializeComponent();
        }

        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            try
            {
                if (MapleCrypto.Initialize() == _ERRCODE.ERR_NOERR)
                {
                    byte[] IV = HexEncoding.GetBytes(txtIV.Text, 0);
                    byte[] Input = HexEncoding.GetBytes(txtInput.Text, 0);
                    bool PacketComplete = false;
                    while (PacketComplete == false)
                    {
                        byte[] Header = new byte[4];
                        System.Buffer.BlockCopy(Input, 0, Header, 0, 4);
                        int PacketLength = MapleCrypto.GetPacketLengthFromHeader(Header);
                        byte[] Data = new byte[PacketLength];
                        Utils.CopyBytes(Data, 0, Input, 4, PacketLength);
                        byte[] Output = new byte[PacketLength];
                        MapleCrypto.Decrypt(IV, Data, Output, PacketLength);
                        MapleCrypto.GenerateIV(IV);

                        Input = Utils.ReplaceBytes(Input, PacketLength + 4);
                        if (Input.Length == 1)
                        {
                            PacketComplete = true;
                        }

                        txtOutput.AppendText(HexEncoding.ToString(Output) + "\r\n\r\n");
                        txtIV.Text = HexEncoding.ToString(IV);
                    }
                }
                else
                {
                    MessageBox.Show("There was a problem initializing the MapleStory Encryption Protocol DLL.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnOutputClear_Click(object sender, EventArgs e)
        {
            txtOutput.Clear();
        }

        private void btnInputClear_Click(object sender, EventArgs e)
        {
            txtInput.Clear();
        }
    }
}
//Created by Arcdemon//
//MapleCryptoAPI by aegisrunestone//
//Utilities class by aegisrunestone//
//Buffer class by aegisrunestone//